package com.lemon.boot.common.config;

import cn.hutool.extra.spring.SpringUtil;
import com.lemon.boot.common.consts.RedisKeyConst;
import com.lemon.boot.common.entity.LoginUserDetail;
import com.lemon.boot.common.service.RedisService;
import com.lemon.boot.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author 李猛
 * @datetime 2023/12/15 12:56
 * @description 类对象
 */
@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfiguration extends ServerEndpointConfig.Configurator {

    /**
     * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    /**
     * 建立握手时，连接前的操作
     */
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        //1.这个userProperties 可以通过 session.getUserProperties()获取
        final Map<String, Object> userProperties = sec.getUserProperties();

        //2.获取websocket固定头 Sec-WebSocket-Protocol
        List<String> secWebSocketProtocolList = request.getHeaders().get(HandshakeRequest.SEC_WEBSOCKET_PROTOCOL);
        if (!CollectionUtils.isEmpty(secWebSocketProtocolList)) {
            //2.1.获取token
            String token = secWebSocketProtocolList.get(0);
            log.info("WebSocketConfiguration.modifyHandshake.token:{}", token);
            if (StringUtils.hasText(token)) {
                //2.2.验证token
                LoginUserDetail currentUser = JwtUtil.getCurrentUser(token);
                RedisService redisService = SpringUtil.getBean(RedisService.class);
                String key = String.format("%s%s", RedisKeyConst.REDIS_KEY_LOGIN_USER, currentUser.getUsername());
                boolean hasUser = redisService.has(key);
                if (hasUser) {
                    userProperties.put("id", currentUser.getUserId());
                    /**
                     * 2.3.响应时必须携带token，不然会报错：java.io.EOFException
                     * 参考文章：https://blog.csdn.net/qq_34168515/article/details/108009811
                     */
                    response.getHeaders().put(HandshakeRequest.SEC_WEBSOCKET_PROTOCOL, Collections.singletonList(token));
                }
            }
        }
        super.modifyHandshake(sec, request, response);
    }

    /**
     * 初始化端点对象,也就是被@ServerEndpoint所标注的对象
     */
    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return super.getEndpointInstance(clazz);
    }
}
